package com.wman.sheep.okhttputils.callback;

import android.text.TextUtils;

import com.wman.sheep.R;
import com.wman.sheep.common.application.AbsAppContext;
import com.wman.sheep.common.utils.GsonTool;
import com.wman.sheep.common.utils.TDevice;
import com.wman.sheep.common.utils.ToastUtil;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/2/14.
 */

public abstract class JsonCallback<T> extends AbsCallback<T> {

    private T clazz;

    public JsonCallback(T clazz) {
        this.clazz = clazz;
    }

    //该方法是子线程处理，不能做ui相关的工作
    @Override
    public T parseNetworkResponse(Response response) throws Exception {
        String responseData = response.body().string();
        if (TextUtils.isEmpty(responseData)) return null;

        if (clazz == null) {
            return (T) responseData;
        } else {
            return (T) GsonTool.parseOneFromJson(responseData, (Class<Object>) clazz);
        }
    }

    @Override
    public void onError(Call call, Response response, Exception e) {
        super.onError(call, response, e);

        if(0 == TDevice.getNetworkType()){
            ToastUtil.showTextToast(AbsAppContext.resources().getString(R.string.common_check_network));
        }else{
            ToastUtil.showTextToast(AbsAppContext.resources().getString(R.string.common_net_error));
        }
    }
}